package com.dsg.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.dao.system.DsgSysFileMapper;
import com.dsg.entity.apply.DsgApplyBill;
import com.dsg.entity.dto.CusEnclDto;
import com.dsg.entity.system.DsgSysFile;
import com.dsg.service.apply.IDsgApplyBillService;
import com.dsg.service.system.IDsgSysFileService;
import com.dsg.util.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.xerces.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统文件存储表 服务实现类
 * </p>
 *
 * @author system
 * @since 2020-07-11
 */
@Slf4j
@Service
public class DsgSysFileServiceImpl extends ServiceImpl<DsgSysFileMapper, DsgSysFile> implements IDsgSysFileService {

    @Autowired
    private DsgSysFileMapper dsgSysFileMapper;
    @Autowired
    IDsgApplyBillService billService;

    @Override
    public List<CusEnclDto> selectCusEncl(String cusNo, String createTimeBegin, String createTimeEnd, String carNo, String appNo, String entCode) {
        return baseMapper.selectCusEncl(cusNo, createTimeBegin, createTimeEnd, carNo, appNo, entCode);
    }


    @Override
    public void saveFile(DsgSysFile dsgSysFile, File file, String oid, String fileType) throws Exception {
        //选删除旧的附件
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("REL_ID", oid);
        wrapper.eq("APP_NO", dsgSysFile.getAppNo());
        wrapper.eq("ENCL_TYPE", dsgSysFile.getEnclType());
        baseMapper.delete(wrapper);

        //保存文件
        InputStream is = new FileInputStream(file);
        byte[] bytes = FileCopyUtils.copyToByteArray(is);
        dsgSysFile.setOid(UUIDGenerator.getUUID());
        dsgSysFile.setRelId(oid);
        dsgSysFile.setFileContent(bytes);
        dsgSysFile.setFileType(fileType);
        dsgSysFileMapper.insert(dsgSysFile);
    }

    @Override
    public DsgSysFile getFile(String pid) {
        QueryWrapper<DsgSysFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("REL_ID", pid);
        DsgSysFile dsgSysFile = dsgSysFileMapper.selectOne(queryWrapper);
        return dsgSysFile;
    }

    @Override
    public List<DsgSysFile> listByBill(String appNo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", appNo);
        List<DsgSysFile> list = list(wrapper);
        DsgApplyBill bill = billService.getOne(wrapper);
        if (!bill.getAppNo().equals(bill.getMainNo())) {
            wrapper = new QueryWrapper();
            wrapper.eq("APP_NO", bill.getMainNo());
            wrapper.in("ENCL_TYPE", paymentEnclList);
            List<DsgSysFile> fileList = list(wrapper);
            if (CollectionUtil.isNotEmpty(fileList)) {
                list.addAll(fileList);
            }
        }

//        for (DsgSysFile encl :list) {
//            String fileType = encl.getFileType();
//
//            if (isImage(fileType)) {
//                String base64Str = Base64.encode(encl.getFileContent());
//                encl.setBase64(base64Str);
//            }
//            encl.setFileContent(null);
//        }
        return list;
    }

    @Override
    public List<DsgSysFile> listByType(String appNo, String enclTypes) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", appNo);
        wrapper.in("ENCL_TYPE", Arrays.asList(enclTypes.split(",")));
        List<DsgSysFile> list = list(wrapper);

        wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", appNo);
        DsgApplyBill bill = billService.getOne(wrapper);

        //付款資料附件的APP_NO實際是申請單的MAIN_NO
        if (!bill.getAppNo().equals(bill.getMainNo())) {
            wrapper = new QueryWrapper();
            wrapper.eq("APP_NO", bill.getMainNo());
            wrapper.in("ENCL_TYPE", paymentEnclList);
            List<DsgSysFile> fileList = list(wrapper);
            for (DsgSysFile file : fileList) {
                boolean exist = false;
                for (DsgSysFile f : list) {
                    if (f.getOid().equals(file))
                        exist = true;
                }
                if (!exist)
                    list.add(file);
            }
        }

        setBase64(list);
        return list;
    }

    private static List<String> paymentEnclList = new ArrayList<>();
    static  {
        paymentEnclList.add(DsgSysFile.ENCL_TYPE_3);
        paymentEnclList.add(DsgSysFile.ENCL_TYPE_4);
        paymentEnclList.add(DsgSysFile.ENCL_TYPE_11);
        paymentEnclList.add(DsgSysFile.ENCL_TYPE_12);
        paymentEnclList.add(DsgSysFile.ENCL_TYPE_13);
        paymentEnclList.add(DsgSysFile.ENCL_TYPE_14);
    }

    private void setBase64(List<DsgSysFile> list) {
        for (DsgSysFile encl :
                list) {
            String fileType = encl.getFileType();

            if (isImage(fileType)) {
                String base64Str = Base64.encode(encl.getFileContent());
                encl.setBase64(base64Str);
            }
        }
    }

    @Override
    public boolean isImage(String fileType) {
        if ("JPG".equalsIgnoreCase(fileType)
                || "JPEG".equalsIgnoreCase(fileType)
                || "PNG".equalsIgnoreCase(fileType)
        ) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void downloadTemplateFile(String fileName, HttpServletResponse response) throws Exception {
        InputStream inputStream = null;
        try {
            //获取目标文件
            Resource[] fileResource = new PathMatchingResourcePatternResolver().getResources("classpath:importTemplate" + File.separator + fileName);
            if (fileResource.length > 0) {
                inputStream = fileResource[0].getInputStream();
                response.reset();
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.addHeader("Content-Length", "" + fileResource[0].contentLength());
                response.setContentType("application/octet-stream");
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                int bytes = 0;
                byte[] buffer = new byte[1024];
                while ((bytes = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytes);
                }
                outputStream.flush();
                outputStream.close();
            } else {
                log.info("模板文件不存在");
                throw new RRException("模板文件不存在");
            }
        } finally {
            if(inputStream != null){
                inputStream.close();
            }
        }
    }
}
